/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.client.impl.consumer;

import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.common.ServiceThread;
import org.apache.rocketmq.common.utils.ThreadUtils;
import org.apache.rocketmq.logging.InternalLogger;

import java.util.concurrent.*;

/**
 * PullMessageService push模式下轮询拉取broker的消息
 */
public class PullMessageService extends ServiceThread {
    private final InternalLogger log = ClientLogger.getLog();
    /**
     * 拉取消息请求的阻塞队列：每个topic分区对应一个请求，表示拉取哪个topic下的哪个分区队列的消息请求
     * 请求什么时候进入阻塞队列的？
     *  （1）consumer启动时，RebalanceImpl 负载均衡器会根据负载均衡算法计算出当前消费者须要消费的队列，topic的每个分区队列构建一个pullRequest , 而后放入队列pullRequestQueue
     *  （2）consumer发送pull请求后，broker服务端处理请求后，响应给客户端时执行回调函数pullCallback，再将pullRequest归还到pullRequestQueue队列继续轮询
     */
    private final LinkedBlockingQueue<PullRequest> pullRequestQueue = new LinkedBlockingQueue<PullRequest>();
    
    private final MQClientInstance mQClientFactory;
    private final ScheduledExecutorService scheduledExecutorService = Executors
        .newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "PullMessageServiceScheduledThread");
            }
        });

    public PullMessageService(MQClientInstance mQClientFactory) {
        this.mQClientFactory = mQClientFactory;
    }

    public void executePullRequestLater(final PullRequest pullRequest, final long timeDelay) {
        if (!isStopped()) {
            this.scheduledExecutorService.schedule(new Runnable() {
                @Override
                public void run() {
                    PullMessageService.this.executePullRequestImmediately(pullRequest);
                }
            }, timeDelay, TimeUnit.MILLISECONDS);
        } else {
            log.warn("PullMessageServiceScheduledThread has shutdown");
        }
    }

    //将pullRequest请求归还到轮询拉取消息的阻塞队列pullRequestQueue中
    public void executePullRequestImmediately(final PullRequest pullRequest) {
        try {
            this.pullRequestQueue.put(pullRequest);
        } catch (InterruptedException e) {
            log.error("executePullRequestImmediately pullRequestQueue.put", e);
        }
    }

    //pullRequest请求延迟归还到轮询拉取消息的阻塞队列pullRequestQueue中
    public void executeTaskLater(final Runnable r, final long timeDelay) {
        if (!isStopped()) {
            this.scheduledExecutorService.schedule(r, timeDelay, TimeUnit.MILLISECONDS);
        } else {
            log.warn("PullMessageServiceScheduledThread has shutdown");
        }
    }

    public ScheduledExecutorService getScheduledExecutorService() {
        return scheduledExecutorService;
    }

    //拉取broker服务端的消息，只有push模式下才会定时去broker拉消息，然后提交给消费消除处理消息
    private void pullMessage(final PullRequest pullRequest) {
        final MQConsumerInner consumer = this.mQClientFactory.selectConsumer(pullRequest.getConsumerGroup());
        if (consumer != null) {
            //强转：推送模式消费者
            DefaultMQPushConsumerImpl impl = (DefaultMQPushConsumerImpl) consumer;
            //拉消息：将pull请求发送给broker服务端 --》broker服务端响应请求 --》执行pull请求回调函数pullCallback --》再将pullRequest归还到pullRequestQueue队列继续下一轮
            impl.pullMessage(pullRequest);
        } else {
            log.warn("No matched consumer for the PullRequest {}, drop it", pullRequest);
        }
    }

    /**
     * consumer轮询拉取消息的任务线程：consumer客户端不断循环拉取broker消息，每次拉取一批消息(默认是32条信息)
     *     push模式下：consumer客户端在启动后，在负载均衡时，将topic下的每个分区都初始化成对应一个PullRequest，一个topic分区对应一个PullRequest，放入这个队列
     *     pull模式下：拉取消息任务线程的pullRequestQueue队列不会被初始化，所以，只会一直空循环，不会发送requestPull请求到broker中拉取消息
     */
    @Override
    public void run() {
        log.info(this.getServiceName() + " service started");
        //push模式：不断循环拉取broker中的消息
        while (!this.isStopped()) {
            try {
                //从队列里获取拉取消息pull请求(pull模式下，pullRequestQueue为空，只有push模式下，才会去broker拉取消息)
                PullRequest pullRequest = this.pullRequestQueue.take();
                //消费者拉取消息：将pull请求发送给broker服务端 --》broker服务端响应请求 --》执行pull请求回调函数pullCallback --》再将pullRequest归还到pullRequestQueue队列继续轮询
                this.pullMessage(pullRequest);
            } catch (InterruptedException ignored) {
            } catch (Exception e) {
                log.error("Pull Message Service Run Method exception", e);
            }
        }
        log.info(this.getServiceName() + " service end");
    }

    @Override
    public void shutdown(boolean interrupt) {
        super.shutdown(interrupt);
        ThreadUtils.shutdownGracefully(this.scheduledExecutorService, 1000, TimeUnit.MILLISECONDS);
    }

    @Override
    public String getServiceName() {
        return PullMessageService.class.getSimpleName();
    }

}
